package com.aditya.testmvcapp.persistence;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.aditya.testmvcapp.domain.Product;

@Component
public class ApplicationDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	private String SELECT_PRODUCTS = "select * from Products";
	
	private String INSERT_PRODUCT = "insert into products(id,description,price) values(?,?,?)";
	
	private String SELECT_PRODUCT = "select * from Products where description = (?)";
	
	private String UPDATE_PRODUCT = "update products set price = (?) where id = (?)";
	
	public List<Product> getProducts() throws DataAccessException{
		List<Product> products = jdbcTemplate.query(SELECT_PRODUCTS, new RowMapper<Product>() {
			@Override
			public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				Product product = new Product();
				product.setId(rs.getInt("id"));
				product.setDescription(rs.getString("description"));
				product.setPrice(rs.getDouble("price"));
				return product;
			}
		});
		return products;
	}
	
	public int addProduct(Product product) throws DataAccessException{
		int insertedrow = jdbcTemplate.update(INSERT_PRODUCT, product.getId(),product.getDescription(),product.getPrice());
		return insertedrow;
	}
	
	public Product getProduct(String description) throws DataAccessException{
		Product product = jdbcTemplate.queryForObject(SELECT_PRODUCT, new Object[]{description}, new RowMapper<Product>() {

			@Override
			public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				Product product = new Product();
				product.setId(rs.getInt("id"));
				product.setDescription(rs.getString("description"));
				product.setPrice(rs.getDouble("price"));
				return product;
			}
		});
		
		return product;
	}

	public void updateProduct(Product product) throws DataAccessException{
		// TODO Auto-generated method stub
		jdbcTemplate.update(UPDATE_PRODUCT, product.getPrice(),product.getId());
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}
